/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package crm.salesOrderProcessing.managedbean;

import frm.creditControl.util.exception.CreditAccountFrozenException;
import frm.creditControl.util.exception.CreditLimitExceededException;
import java.io.IOException;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import mrp.productionPlanning.util.exception.ATPFailedException;
import crm.salesOrderProcessing.entity.LineItemEntity;
import crm.salesOrderProcessing.entity.SalesOrderEntity;
import crm.salesOrderProcessing.entity.SalesQuotationEntity;
import crm.salesOrderProcessing.session.PriceManagementSessionBean;
import crm.salesOrderProcessing.session.ProductManageSessionBean;
import crm.salesOrderProcessing.session.SalesOrderSessionBean;
import crm.salesOrderProcessing.session.SalesQuotationSessionBean;
import scm.supplyChainManagement.session.InventorySessionBean;

/**
 *
 * @author ReinForceII
 */
@ManagedBean
@ViewScoped
public class VerifySalesOrderManagedBean {

    @EJB
    SalesOrderSessionBean salesOrderSessionBean;
    @EJB
    SalesQuotationSessionBean salesQuotationSessionBean;
    @EJB
    ProductManageSessionBean productManageSessionBean;
    @EJB
    PriceManagementSessionBean priceManageSessionBean;
    @EJB
    InventorySessionBean inventorySessionBean;
    private SalesOrderEntity salesOrder;
    private LineItemEntity lineItem;
    private List<LineItemEntity> lineItemList;
    private Long salesOrderId;
    private Long quotationId;
    private Long companyId;
    private Long productId;
    private String productName;
    private String errorMessage;
    private SalesQuotationEntity salesQuotation;
    private List<LineItemEntity> quotationLineItemList;
    private boolean changed = false;

    /** Creates a new instance of AmendPurchaseOrderManagedBean */
    public VerifySalesOrderManagedBean() {
        salesOrder = doIni();
    }

    private SalesOrderEntity doIni() {
        if (salesOrder == null) {
            salesOrder = (SalesOrderEntity) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("purchaseOrder");
        }
        return salesOrder;
    }

    public void verifyPurchaseOrder(ActionEvent event) throws Exception {
        double totalAmount = 0;
        double creditAmount = 0;

        if (salesOrder.getStatusId() != 200) {
            setErrorMessage("Salesorder status mismatch, current status Id: " + salesOrder.getStatusId());
            return;
        }
        lineItemList = salesOrder.getSalesOrderLineItems();
        if (lineItemList.isEmpty()) {
            setErrorMessage("There is no item in the ordering list.");
            return;
        }
        //set the LineItemEntity
        salesOrder.setSalesOrderLineItems(lineItemList);
        for (LineItemEntity item : lineItemList) {
            totalAmount = totalAmount + (item.getCumAmount());
            if (!item.isCashInAdvance()){
                creditAmount = creditAmount + item.getCumAmount();
            }
        }
        salesOrder.setTotalAmount(totalAmount);

        try {

            salesOrderSessionBean.verifySalesOrder(salesOrder);

        } catch (CreditAccountFrozenException e) {
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("msg", "Credit account is frozen. Please pay outstnading bills.");

            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("purchaseOrder", salesOrder);
            FacesContext.getCurrentInstance().getExternalContext().redirect("amendPurchaseOrder.xhtml");
            return;
        } catch (CreditLimitExceededException e) {
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("msg", "No enough credit. Please reduce amount ordered or pay cash in advance.");

            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("purchaseOrder", salesOrder);
            FacesContext.getCurrentInstance().getExternalContext().redirect("amendPurchaseOrder.xhtml");
            return;
        } catch (ATPFailedException e) {

            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("msg", "ATP failed: " + e.getMessage());
            salesOrder.setStatusId(300);
            salesOrder.setDateLastModified(Calendar.getInstance().getTime());
            salesOrderSessionBean.saveChanges(salesOrder);

            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("purchaseOrder", salesOrder);
            FacesContext.getCurrentInstance().getExternalContext().redirect("amendPurchaseOrder.xhtml");
            return;
        }

        salesOrder.setDateLastModified(Calendar.getInstance().getTime());
        salesOrder.setStatusId(400);

        if (salesOrder.isSkipConfirm()) {
            salesOrder.setStatusId(500);
        }
        //salesOrder.setProcessedBy(salesman);;
        salesOrderSessionBean.saveChanges(salesOrder);
        inventorySessionBean.reserveInventory(salesOrder);

        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("lastURL", "verifySalesOrder");
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("purchaseOrder", salesOrder);
        FacesContext.getCurrentInstance().getExternalContext().redirect("salesOrderactionResult.xhtml");

        return;

    }

    public void reDirect() throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().redirect("viewAllPurchaseOrder.xhtml");
    }

    public LineItemEntity getLineItem() {
        return lineItem;
    }

    public void setLineItem(LineItemEntity lineItem) {
        this.lineItem = lineItem;
    }

    public Collection<LineItemEntity> getLineItemList() {
        return lineItemList;
    }

    public void setLineItemList(List<LineItemEntity> lineItemList) {
        this.lineItemList = lineItemList;
    }

    public SalesOrderEntity getSalesOrder() {
        return salesOrder;
    }

    public void setSalesOrder(SalesOrderEntity salesOrder) {
        this.salesOrder = salesOrder;
    }

    public Long getQuotationId() {
        return quotationId;
    }

    public void setQuotationId(Long quotationId) {
        this.quotationId = quotationId;
    }

    public Long getCompanyId() {
        return companyId;
    }

    public void setCompanyId(Long companyId) {
        this.companyId = companyId;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    /**
     * @return the salesOrderId
     */
    public Long getSalesOrderId() {
        return salesOrderId;
    }

    /**
     * @param salesOrderId the salesOrderId to set
     */
    public void setSalesOrderId(Long salesOrderId) {
        this.salesOrderId = salesOrderId;
    }

    /**
     * @return the errorMessage
     */
    public String getErrorMessage() {
        return errorMessage;
    }

    /**
     * @param errorMessage the errorMessage to set
     */
    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    /**
     * @return the salesQuotation
     */
    public SalesQuotationEntity getSalesQuotation() {
        return salesQuotation;
    }

    /**
     * @param salesQuotation the salesQuotation to set
     */
    public void setSalesQuotation(SalesQuotationEntity salesQuotation) {
        this.salesQuotation = salesQuotation;
    }

    /**
     * @return the quotationLineItemList
     */
    public List<LineItemEntity> getQuotationLineItemList() {
        return quotationLineItemList;
    }

    /**
     * @param quotationLineItemList the quotationLineItemList to set
     */
    public void setQuotationLineItemList(List<LineItemEntity> quotationLineItemList) {
        this.quotationLineItemList = quotationLineItemList;
    }

    /**
     * @return the productId
     */
    public Long getProductId() {
        return productId;
    }

    /**
     * @param productId the productId to set
     */
    public void setProductId(Long productId) {
        this.productId = productId;
    }

    /**
     * @return the changed
     */
    public boolean isChanged() {
        return changed;
    }
}